#from django.contrib.auth.models import User
from django.db.models import signals
from django.dispatch import dispatcher
from django.conf import settings


def collect_active_bkend():
    #f = lambda x: not re.search("django|dbframewirk.apps.core",x)
    #apps = filter(f,settings.INSTALLED_BKHAND)
    return settings.INSTALLED_BKENDS

def drop_everithing(mask, instance):
    for bk in mask:
        mask[bk].drop(instance, bk)
        
def post_delete_backend(sender, instance, signal, *args, **kargw):
    bkends = collect_active_bkend()
    mask = {}
    for bk in bkends:
        mask[bk] = __import__(bk, globals() , locals(), ['*'])
    drop_everithing(mask, instance)
    
def post_save_backend(sender, instance, signal, *args, **kargw):
    bkends = collect_active_bkend()
    mask = {}
    for bk in bkends:
        mask[bk] = __import__(bk, globals(), locals(), ['*'])
        status = mask[bk].save(instance, bk)
        if not status:
            break

    if mask.__len__() != bkends.__len__():
        drop_everithing(mask, instance)

dispatcher.connect(post_save_backend, signal=signals.post_save)
dispatcher.connect(post_delete_backend, signal=signals.post_delete)
